//
//  SeleDatePicker.swift
//  inke_ Business
//
//  Created by sh on 17/2/6.
//  Copyright © 2017年 畅联九州. All rights reserved.
//

import UIKit


typealias BackDate = (Date)->Void
typealias CancelClosure = () -> Void

class SeleDatePicker: UIView {
    
    var backClosure: CancelClosure!
    
    var backDate: BackDate!
    
    var datePicker: UIDatePicker!
    
    var starString = ""
    
    var finishString = ""
    
    var date:Date?
    
    override init(frame:CGRect){
        super.init(frame: frame)
        self.clipsToBounds = true
        self.initContent()
        self.backgroundColor = UIColor.white
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initContent(){
        
        let topView = UIView(frame: CGRect(x:0 ,y:0 ,width:self.bounds.size.width ,height:40))
        topView.backgroundColor = UIColor(hexColor: "f0f0f0")
        
        let cancelBtn = UIButton(type: .custom)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.setTitleColor(UIColor(hexColor: "333333"), for: .normal)
        cancelBtn.addTarget(self, action: #selector(btnClick(sender:)), for: UIControlEvents.touchUpInside)
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        cancelBtn.frame = CGRect(x: 8, y: 0, width: 40, height: 40)
        topView.addSubview(cancelBtn)
        
        let confirm = UIButton(type: .custom)
        confirm.setTitle("确定", for: .normal)
        confirm.setTitleColor(UIColor(hexColor: "333333"), for: .normal)
        confirm.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        confirm.addTarget(self, action: #selector(btnClick(sender:)), for: UIControlEvents.touchUpInside)
        confirm.frame = CGRect(x: self.bounds.size.width - 40 - 8, y: 0, width: 40, height: 40)
        topView.addSubview(confirm)
        
        self.addSubview(topView)
        
        self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 40, width: UIScreen.ScreenWidth, height: self.height - 40 - (Utils.isIphoneX() ? 34 : 0)))
        self.datePicker!.timeZone = NSTimeZone.local
        self.datePicker!.locale = Locale.init(identifier: "zh_CN")
        self.datePicker!.date = Date()
        self.datePicker.maximumDate = Date()
        self.datePicker!.addTarget(self, action: #selector(datePickerValueChanged(picker:)), for: UIControlEvents.valueChanged)
        self.datePicker!.datePickerMode = UIDatePickerMode.date
        self.addSubview(self.datePicker!)
        
        self.date = Date().currentDayzeroOfDate.passDate()
    }
    
    @objc func btnClick(sender:UIButton){
        if sender.titleLabel?.text == "取消" {
            self.backClosure()
            
        }else {
            if (self.backDate != nil) {
                self.backDate(self.date!)
            }
        }
    }
    
    @objc func datePickerValueChanged(picker:UIDatePicker){
        let date = picker.date.passDate()
        self.date = date
    }

}
